package codeRandomThoughts.Test72编辑距离;

public class Solution {
    public int minDistance(String word1, String word2) {
        char[] char1 = word1.toCharArray();
        char[] char2 = word2.toCharArray();

        //dp[i][j]:以i-1为结尾的word1转换为以j-1为结尾的word2所用最少操作数
        int[][] dp = new int[char1.length + 1][char2.length + 1];

        //初始化
        for (int i = 0; i <= char1.length; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= char2.length; j++) {
            dp[0][j] = j;
        }

        //递推
        for (int i = 1; i <= char1.length; i++) {
            for (int j = 1; j <= char2.length; j++) {
                if (char1[i - 1] == char2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    int min = Math.min(dp[i][j - 1], dp[i - 1][j]);
                    dp[i][j] = Math.min(dp[i - 1][j - 1], min) + 1;
                }
            }
        }
        return dp[char1.length][char2.length];
    }
}